<template>
  <div class="map-container">
    <div class="gnssBg">GNSS{{ $t("home.gnss") }}</div>
    <div ref="chartRef" class="chart-container"></div>
    <!-- 加载状态提示（保留，按需启用） -->
    <!-- <div v-if="isLoading" class="loading-mask">
      <div class="spinner"></div>
      <p>地图加载中...</p>
    </div> -->
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from "vue";
import * as echarts from "echarts/core";
import { GeoComponent, TooltipComponent } from "echarts/components";
import { MapChart, ScatterChart, LinesChart } from "echarts/charts";
import { CanvasRenderer } from "echarts/renderers";
import { airportsApi, getWayPointsApi } from "@/api/home";

// 注册所需模块（保持不变）
echarts.use([
  GeoComponent,
  MapChart,
  ScatterChart,
  LinesChart,
  CanvasRenderer,
  TooltipComponent,
]);

// 组件状态（保持不变）
const chartRef = ref(null);
const chart = ref(null);
const isReady = ref(false);
// const isLoading = ref(true); // 加载状态管理

// 地图常量配置（保持不变）
const MAP_CONFIG = {
  // center: [105, 30],
  // zoom: 1.2,
  backgroundColor: "transparent",
  // areaColor: "#e6f7ff",
  // borderWidth: 1,
  // borderColor: "rgba(0, 0, 0, 0.2)",
  // beijingCoord: [116.4, 39.9],
};

// 异步加载地图数据（保持不变）
const loadMapData = async () => {
  try {
    const { default: chinaJson } = await import("@/assets/china.json");
    echarts.registerMap("china", chinaJson);
    return true;
  } catch (error) {
    console.error("地图数据加载失败:", error);
    return false;
  }
};

// 初始化图表（核心修复处）
const initChart = () => {
  if (!isReady.value || !chart.value) return;
  const option = {
    backgroundColor: MAP_CONFIG.backgroundColor,
    tooltip: { show: false }, // 全局关闭提示框，彻底禁用鼠标移入提示
    geo: {
      map: "china",
      aspectScale: 0.75,
      layoutCenter: ["50%", "41.5%"],
      layoutSize: "70%",
      roam: false, // 保留地图缩放平移（如需关闭可改为false）
      // 1. 禁用geo组件的省份交互：清空所有emphasis配置
      emphasis: {
        disabled: true, // 关键：直接禁用geo组件的交互状态（彻底失效）
      },
      itemStyle: {
        normal: {
          borderColor: "#4896a4",
          borderWidth: 0.5,
          color: {
            type: "linear-gradient",
            x: 0,
            y: 1500,
            x2: 2500,
            y2: 0,
            colorStops: [
              { offset: 0, color: "#132c5f" },
              { offset: 1, color: "#132c5f" },
            ],
            global: true,
          },
          opacity: 0.5,
        },
        // 兜底：即使disabled失效，也让交互样式与正常样式一致
        emphasis: {
          areaColor: "rgba(0, 157, 161, 0.5)", // 与normal的areaColor透明度一致
          borderColor: "rgba(147, 235, 248, 1)", // 与normal的borderColor一致
        },
      },
      regions: [
        {
          name: "南海诸岛",
          itemStyle: {
            areaColor: "rgba(0, 10, 52, 1)",
            borderColor: "rgba(0, 10, 52, 1)",
          },
          // 同步禁用南海诸岛交互
          emphasis: {
            areaColor: "rgba(0, 10, 52, 1)",
            borderColor: "rgba(0, 10, 52, 1)",
          },
        },
      ],
      z: 2,
    },
    series: [
      {
        type: "map",
        map: "china",
        tooltip: { show: false }, // 关闭该series的提示框
        label: {
          show: false,
          color: "#FFFFFF", // 正常状态字体颜色
          fontSize: 12, // 已减小的字体大小
          // 2. 修复：清空label的emphasis，防止鼠标移入字体变色
          emphasis: {
            color: "#FFFFFF", // 强制交互时字体颜色与正常状态一致
            fontWeight: "normal", // 取消交互时字体加粗（如有）
          },
        },
        aspectScale: 0.75,
        layoutCenter: ["50%", "40%"],
        layoutSize: "70%",
        roam: false,
        // 3. 禁用series的省份交互：直接禁用emphasis状态
        emphasis: {
          disabled: true, // 关键：彻底禁用该series的交互状态
        },
        itemStyle: {
          normal: {
            borderColor: "rgba(147, 235, 248, 0.6)",
            borderWidth: 0.8,
            areaColor: {
              type: "linear-gradient",
              x: 0,
              y: 1200,
              x2: 1000,
              y2: 0,
              colorStops: [
                { offset: 0, color: "#132c5f" },
                { offset: 1, color: "#132c5f" },
              ],
              global: true,
            },
          },
          // 兜底：即使disabled失效，交互样式与正常样式一致
          emphasis: {
            areaColor: "rgba(0, 157, 161, 0.5)",
            borderColor: "rgba(147, 235, 248, 0.6)",
          },
        },
        zlevel: 1,
      },
    ],
  };
  chart.value.setOption(option);
  getAirportsApi(); // 保持机场接口调用
};

// 以下所有函数（获取机场、绘制航路等）
const getAirportsApi = async () => {
  const { code, data } = await airportsApi();
  if (code === 200) {
    const newArrs = data.list.map((item) => ({
      name: item.city,
      value: [item.longitude, item.latitude],
    }));
    airportCoordinates(newArrs);
  }
};
// import greenPlaneImg from "../../../assets/images/home/airlvicon.png";
const airportCoordinates = (newArrs) => {
  const greenPlane = new URL(
    "../../../assets/images/home/airlvicon.png",
    import.meta.url
  ).href;
  console.log("图片路径：", greenPlane); // 打印路径，在浏览器控制台查看是否能访问
  // const greenPlane = "../../../assets/images/home/airlvicon.png";
  // import greenPlaneImg from '../../../assets/images/home/airlvicon.png';
  // const redPlane = "images/red_plane.png";
  const scatterSeries = {
    type: "scatter",
    coordinateSystem: "geo",
    name: "机场位置",
    data: newArrs.map((item) => {
      // 假设接口返回数据中包含 can 字段（1 为绿色，否则红色）
      // const isGreen = item.can === 1;
      return {
        ...item,
        // 自定义 symbol：图片路径 + 大小
        // symbol: isGreen ? greenPlane : redPlane,
        symbol: `image://${greenPlane}`,
        symbolSize: [18, 30], // 飞机图片大小，可根据实际调整
      };
    }),
    // symbol: "circle",
    // symbolSize: 10,
    // itemStyle: { color: "#ff4d4f", borderColor: "#fff", borderWidth: 2 },
    // emphasis: { symbolSize: 12, itemStyle: { color: "#ff0000" } }, // 机场交互保留（如需移除可清空）
    emphasis: {
      disabled: true,
    },
    zlevel: 3,
  };
  chart.value.setOption({
    series: [...chart.value.getOption().series, scatterSeries],
  });
  getWayPoints();
};
const getWayPoints = async () => {
  try {
    const { code, data: rawData } = await getWayPointsApi();
    if (code === 200) {
      const lineData = rawData.list.map((outerItem) => ({
        name: outerItem.name,
        coords: outerItem.wayPoints.map((point) => [
          point.longitude,
          point.latitude,
        ]),
      }));
      wayPointsCoordinates(lineData);
    }
  } catch (error) {
    console.error("获取航路数据失败:", error);
  }
};

const wayPointsCoordinates = (lineData) => {
  if (!isReady.value || !chart.value) return;
  const lineSeriesList = lineData.map((line) => {
    const color = "#a1a1a1";
    const lineColor = color;
    return {
      type: "lines",
      coordinateSystem: "geo",
      geoIndex: 0,
      polyline: true,
      name: line.name,
      data: [
        {
          coords: line.coords,
          lineName: line.name,
        },
      ],
      symbol: ["none", "none"],
      lineStyle: {
        color: lineColor,
        width: 2,
        type: "solid",
        opacity: 0.8,
      },
      tooltip: {
        formatter: (params) => `
          <div style="padding: 5px;">
            <div style="font-weight: 600;">${params.data.lineName}</div>
            <div>经纬度：${params.value[0].toFixed(
              2
            )}, ${params.value[1].toFixed(2)}</div>
          </div>
        `,
      },
      zlevel: 2,
    };
  });
  const existingSeries = chart.value.getOption().series || [];
  chart.value.setOption({
    series: [...existingSeries, ...lineSeriesList],
  });
};

// 组件生命周期（保持不变）
onMounted(() => {
  const initTimer = setTimeout(() => {
    clearTimeout(initTimer);
    nextTick(async () => {
      if (!chartRef.value) return;
      chart.value = echarts.init(chartRef.value, null, {
        renderer: "canvas",
        useDirtyRect: true,
      });
      const dataLoaded = await loadMapData();
      if (!dataLoaded) {
        // isLoading.value = false;
        return;
      }
      isReady.value = true;
      initChart();
      // isLoading.value = false;
    });
  }, 100);
});

watch(
  () => chartRef.value?.clientWidth,
  (newWidth) => {
    if (newWidth && isReady.value) {
      chart.value.resize({ animation: { duration: 300 } });
    }
  }
);

// const handleWindowResize = () => {
//   if (isReady.value) chart.value.resize();
// };
// window.addEventListener("resize", handleWindowResize);

onUnmounted(() => {
  console.log("xiaohui");
  // window.removeEventListener("resize", handleWindowResize);
  if (chart.value) {
    chart.value.dispose();
    chart.value = null;
  }
  isReady.value = false;
});
</script>

<style scoped lang="scss">
/* 样式保持不变 */
.map-container {
  position: relative;
  // width: 920px;
  width: calc(100vw - 520px);
  float: left;
  height: 454px;
  overflow: hidden;
  .gnssBg {
    text-indent: 40px;
    color: #fff;
    text-align: left;
    font-size: 22px;
    font-weight: 700;
    line-height: 42px;
    margin-top: 15px;
    margin-left: 24px;
    width: 436px;
    height: 42px;
    background-image: url("../../../assets/images/home/GNSSBg.png");
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
  }
}
.chart-container {
  // width: 920px;
  width: 100%;
  height: 100%;
}
</style>
